// pages/diaryDetail/index.js
const { getWeek } = require('../../utils/util')
const api = require('../../config/api')
const request = require('../../utils/request')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    diaryInfo: '',
    isCreate: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.isCreate) {
      this.setData({
        isCreate: true,
      })
    }
    this.setData({
      diaryId: options.diaryId,
      // diaryId: 40
    })
    this.getDiaryDetail(options.diaryId)
  },
  getDiaryDetail: async function (diaryId) {
    const res = await request.get(api.diaryDetail + diaryId)
    if (res.httpStatus === 200) {
      const time = res.data.releaseTime.split(' ')
      res.data.releaseTime = time[0].replace(/-/g, '/')
      res.data.weekday = getWeek(res.data.releaseTime)
      res.data.time = time[1].substring(0, 5)
      this.setData({
        diaryInfo: res.data,
      })
    }
  },
  delete() {
    wx.vibrateShort({
      type: 'light',
    })
    const that = this
    wx.showModal({
      content: '确认要删除这条日记吗？',
      cancelText: '取消', //默认是“取消”
      confirmText: '确认', //默认是“确定”
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          that.deleteDiary()
        }
      },
      fail: function (res) {}, //接口调用失败的回调函数
      complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  deleteDiary: async function () {
    const res = await request.get(api.diaryDelete + this.data.diaryId)
    if (res.httpStatus === 200) {
      wx.navigateBack({
        delta: 1,
      })
    }
  },
  // 点击图片放大
  previewImg: function (e) {
    let index = e.currentTarget.dataset.index
    let imgArr = this.data.diaryInfo.imgList
    wx.previewImage({
      current: imgArr[index], //当前图片地址
      urls: imgArr, //所有要预览的图片的地址集合 数组形式
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.isCreate) {
      wx.navigateBack({
        delta: 1,
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
